package com.qst.rongxiaoserver.common;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.util.HashMap;
import java.util.Map;

// 全局异常处理器
// 捕获其他异常，但排除Swagger相关异常
// 捕获其他异常，但排除Swagger相关异常
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    // 处理 @RequestBody @Valid 验证失败的异常
    public Result handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });

        return Result.fail("Validation failed", errors);
    }

    @ExceptionHandler(BindException.class)
    // 处理 @RequestParam @Valid 验证失败的异常
    public Result handleBindExceptions(BindException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        return Result.fail("Binding failed", errors);
    }

    // 捕获其他异常，但排除Swagger相关异常
    @ExceptionHandler(Exception.class)
    public Result handleGenericException(Exception e) {
        // 排除Swagger相关路径的异常处理
        if (e instanceof NoResourceFoundException) {
            // 让Spring Boot默认处理静态资源和Swagger资源
            throw new RuntimeException(e);
        }

        // 记录日志
        e.printStackTrace();
        return Result.fail("Internal server error: " + e.getMessage());
    }
}
